<template>
	<div class="address-List" v-if="list.length > 0">
		<el-card class="box-card" v-for="(item, index) in list" :key="index">
			<AddressItem
				:item="item.addressItem"
				:defaultItem="item.defaultAddressItem"
				:loading="item.addressLoading"
				@submit="(item) => editItem(item, index)"
			/>

			<!-- <div class="box-card-item">{{ item.firstName }},{{ item.lastName }},{{ item.phoneNumber }}</div>
			<div class="box-card-item">{{ item.country }},{{ item.city }},{{ item.detailAddress }}</div>
			<div class="box-card-item">
				{{ item.postCode }}
			</div> -->
		</el-card>
	</div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import AddressItem from './addressItem.vue';
import { useCustomerApi } from '/@/api/customer';
const { UpdateCustomerAddress } = useCustomerApi();
const emit = defineEmits(['update:list', 'reload']);
const props = defineProps({
	list: {
		type: Array,
		default: () => {
			return [];
		},
	},
	customerId: {
		type: Number,
		default: -1,
	},
});

async function editItem(item, index) {
	try {
		let newList = props.list;
		newList[index].addressLoading = true;
		let params = {};
		let res = null;
		// 修改
		params = {
			id: item.id,
			memberId: props.customerId,
			defaultStatus: item.isDefault ? 1 : 0,
			mark: item.label,
			firstName: item.firstName,
			lastName: item.lastName,
			detailAddress: item.address,
			city: item.city,
			country: item.countryValue,
			postCode: item.postCode,
			phoneNumber: item.phone,
		};
		res = await UpdateCustomerAddress(params);

		if (res.code !== 200) {
			newList[index].addressLoading = false;
			return;
		}
		ElMessage({
			type: 'success',
			message: '保存成功！',
		});
		newList[index].addressLoading = false;
		emit('update:list', newList);
		emit('reload');
	} catch (error) {
		newList[index].addressLoading = false;
		ElMessage({
			type: 'error',
			message: '保存失败',
		});
	}
}
</script>
<style lang="scss">
.address-List {
	padding: 20px;
	display: flex;
	flex-direction: column;
	overflow-y: auto;
	height: 100%;
	.box-card {
		margin-bottom: 20px;
		overflow: visible;
	}
	.address-for-item {
		padding: 10px;
		border: 1px solid #dddddd;
		margin-bottom: 20px;
	}
}
</style>
